package com.cygsunri.common.exception;

import com.cygsunri.common.enume.EnumConstant;
import com.cygsunri.common.response.ResultWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 全局统一异常处理器
 * </p>
 *
 * @author cygsunri
 * @since 2021/7/01
 */
@Slf4j
@RestControllerAdvice
public class GlobalManagerExceptionHandler implements Serializable {
    private static final long serialVersionUID = -3967569479917062550L;

    /**
     * 全局数据校验出现问题
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultWrapper<Object> handleVaildException(MethodArgumentNotValidException e){
        log.error("vaildException ======>数据校验异常{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return ResultWrapper.error(EnumConstant.BizCodeEnume.VAILD_EXCEPTION.getValue(),EnumConstant.BizCodeEnume.VAILD_EXCEPTION.getName(),errorMap);
    }

    /**
     * 全局异常
     *
     * @param e Exception
     * @return ResultWrapper
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResultWrapper<Exception> globalException(Exception e) {
        log.error("globalException ======> 全局异常:{},异常类型:{}", e.getMessage(), e.getClass());
        return ResultWrapper.error(e);
    }

    /**
     * 自定义业务异常
     *
     * @param e BusinessException
     * @return ResultWrapper
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultWrapper<BusinessException> businessException(BusinessException e) {
        log.error("businessException ======> 自定义异常: {},异常类型", e.getMessage(), e.getClass());
        return ResultWrapper.error(e);
    }
}
